package android.test.zoom;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.ViewCompat;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

/**
 * Created by dinhthao on 7/3/13.
 */
public class MyView extends View {


    public MyView(Context context) {
        super(context);
    }

    private RectF mCurentViewport = new RectF(100, 100, 1000, 1000);
    private Rect mRect;
    private ScaleGestureDetector mScaleGestureDetector;

    private final ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener
            = new ScaleGestureDetector.SimpleOnScaleGestureListener() {

        private PointF viewportFocus = new PointF();
        private float lastSpanX;
        private float lastSpanY;

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
           lastSpanX = detector.getCurrentSpanX();
           lastSpanY = detector.getCurrentSpanY();
            return true;
        }

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float spanX = detector.getCurrentSpanX();
            float spanY = detector.getCurrentSpanY();
            float newWidth = lastSpanX/spanX * mCurentViewport.width();
            float newHeight = lastSpanY/spanY * mCurentViewport.height();

            float focusX = detector.getFocusX();
            float focusY = detector.getFocusY();
            mCurentViewport.set(viewportFocus.x - newWidth * (focusX - mRect.left)/mRect.width(), viewportFocus.y - newHeight
            *(mRect.bottom - focusY)/mRect.height(), 0, 0);

            mCurentViewport.right = mCurentViewport.left + newWidth;
            mCurentViewport.bottom = mCurentViewport.top + newHeight;
            ViewCompat.postInvalidateOnAnimation(getRootView());

            lastSpanY = spanY;
            lastSpanX = spanX;

            return true;
        }
    };


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        canvas.drawCircle(100, 200, 20, paint);

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean retVal = mScaleGestureDetector.onTouchEvent(event);
        retVal = mScaleGestureDetector.onTouchEvent(event) || retVal;
        return retVal || super.onTouchEvent(event);
    }



}
